<template>
    <div>
      
      <div class="jopTitle">
      <el-row >
        <el-col :span="5">
          <el-button type="warning" size="mini" class="el-icon-plus" @click="dialogFormVisible = true">添加</el-button>
          <el-button style="margin-left:20px;" type="danger"  size="mini" class="el-icon-circle-close-outline" @click="deleteAll" >批量删除</el-button>
        </el-col>
        <el-col :span="5" >
                    <el-autocomplete
                      class="inline-input"
                      size="mini" 
                      v-model="property"
                      :fetch-suggestions="propertyMethod"
                      placeholder="岗位属性"
                      @select="propertyChange"
                      value-key="name"
                    ></el-autocomplete>
         </el-col>
         <el-col :span="5">
                    <el-autocomplete
                      size="mini"
                      v-model="pName"
                      :fetch-suggestions="querySearchAsync"
                      placeholder="组织选择"
                      @select="selectOrg"
                      :trigger-on-focus="false"
                      value-key="name"
                    ></el-autocomplete>
          </el-col>

          <el-col :span="6">
          <el-input
            style="margin-left:20px;"
            placeholder="请输入履职说明书标题/内容"
            size="mini"
            v-model="keywords">
            <i slot="prefix" class="el-input__icon el-icon-search"></i>
          </el-input>

        </el-col>
      </el-row>
      </div>
      <el-table
        ref="multipleTable"
        :data="tableData"
        tooltip-effect="dark"
        style="width: 100%"
        @selection-change="handleSelectionChange">

        <el-table-column
          type="selection"
          width="55">
        </el-table-column>

        <el-table-column prop="title" label="履职说明书标题"  show-overflow-tooltip></el-table-column>

        <el-table-column prop="userName" label="姓名"  show-overflow-tooltip></el-table-column>

        <el-table-column prop="orgName" label="所属组织"  show-overflow-tooltip></el-table-column>

        <el-table-column prop="stationName" label="岗位属性"  show-overflow-tooltip></el-table-column>

        <el-table-column prop="uploadTime" label="上传时间"  show-overflow-tooltip></el-table-column>

         <el-table-column  label="操作" >
          <template slot-scope="scope">
            <el-button @click="deleteClick(scope.row)" type="text" size="small">删除</el-button>
            <span>|</span>
            <el-button @click="remakeClick(scope.row)" type="text" size="small">编辑</el-button>
          </template>
       </el-table-column>
      </el-table>
      <pager ref="pager"  v-on:listenPagerEvent="getPagerData" :requestUrl="requestUrl" :requestParams="requestParams"></pager>

      <el-dialog title="添加履职说明书" :visible.sync="dialogFormVisible">
        <el-form :model="upDataForm">
          <el-form-item label="人员组织" :label-width="formLabelWidth">
            <el-autocomplete
                  size="mini"
                  v-model="upDataForm.pName"
                  :fetch-suggestions="searchOrg"
                  placeholder="请输入组织名称（必填）"
                  @select="handleSelectOrg"
                  :trigger-on-focus="false"
                  value-key="name"
            ></el-autocomplete>
          </el-form-item>
          <el-form-item label="人员信息" :label-width="formLabelWidth">
            <el-select size="mini" @change="personSelect" v-model="upDataForm.userName" style="width:100%" filterable placeholder="请选择人员">
              <el-option
              v-for="item in options"
              :label="item.userName"
              :value="item.userId"
              :key="item.userId"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="说明书标题" :label-width="formLabelWidth">
            <el-input size="mini" v-model="upDataForm.title" auto-complete="off" placeholder="请输入履职说明书标题（必填，限28字）"></el-input>
          </el-form-item>
          <el-form-item label="选择文件" :label-width="formLabelWidth">
            <el-input style="width:240px;height:20px;" v-model="fileName" size="mini" readonly placeholder="请选择（仅支持.pdf格式文件）"></el-input>
            <el-upload style="display:inline-block;position:absolute;left:260px;height:30px" ref="upload"
              name="fileName"
              id="fileName"
              :action="uploadUrl"
              accept='.pdf'
              :multiple="false"
              :limit=1
              :show-file-list="false"
              :before-upload="beforeLoad"
              :on-success="successRes"
              :on-error="errorRes"
              :auto-upload="false"
              :data="formData"
              :on-change="fileChecked"
              :headers="headerToken"
              :on-progress="isUpdata">
              <el-button size="mini" type="danger">选择文件</el-button>
            </el-upload>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button size="mini" @click="dialogFormVisible = false">取 消</el-button>
          <el-button size="mini" type="primary"  @click="submitLoadFile">确 定</el-button>
        </div>
    </el-dialog>

    </div>
</template>

<script>
import modal from '../common/modal'
import pager from '../common/pager'
import {
  jobDesPageList,desDoDelete,findOrgList,findPageList,jobDescDoSave,uploadFile,findStationList} from '../../tool/config'
import { Notification , Loading} from 'element-ui'

export default {
  components:{pager},
  data() {	
    return {
        
        options:[],
        value1: '组织选择',
        value2: '岗位属性选择',
        input11:'',
        tableData:[],
        multipleSelection: [],//已选择的数据
        dialogFormVisible: false,
        upDataForm: {
          pName:'',
          userName: '',
          orgId:'',
          title:'',
          userId:'',
          stationId:'',
          fileUrl:''
        },
        formLabelWidth: '120px',
        fileName: '', //文件名称
        formData:{},  //文件导入的其他参数
        requestUrl:jobDesPageList,
        requestParams:{
          keywords:'',
          orgId:'',
          stationId:'',
          reload:'',
        },
        orgNameString:[],
        uploadUrl:'',
        headerToken:{},
        property:'',
        propertyList:[],
        pName:'',
        keywords:'',//搜索输入的关键词
        restaurants:[],
    }
  },
  methods: {
    getPagerData(data){
      console.log(data)
      this.tableData = data;
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    deleteClick(row) {
        this.$confirm('您确认删除' + row.title + '的选项吗', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          desDoDelete({ids:row.id}).then(res=>{
            if(res.code == 0){
              this.requestParams.reload = Math.random();
              this.$message({
                type: 'success',
                message: '删除成功!'
              });
            }else{
              this.$notify({
                title: '提示',
                message: res.msg,
                duration: 3000,
                type: 'warning'
              });
            }
          })
          
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
      },
    remakeClick(row){
      
    },
      //选择文件后
      fileChecked(file,fileList){
        if(fileList.length > 1){
          fileList.splice(0,1)
        };
        this.fileName = file.name;
        this.$refs.upload.submit();

      },
      //上传之前的校验
      beforeLoad(file){
        const isExcel = file.type === 'application/pdf';
        const isLt5M = file.size / 1024 / 1024 < 100;
        if(!isExcel){
          this.$alert('上传文件必须为pdf格式', '提示', {
            type:'info',
            confirmButtonText: '确定',
            showClose:false}).then(function(){return });
        };
        if(!isLt5M){
          this.$alert('上传文件大小不能超过100M', '提示', {
            type:'info',
            confirmButtonText: '确定',
            showClose:false}).then(function(){return});
        }
        return isExcel && isLt5M ;
      },
      //确认导入
      submitLoadFile(){
        var obj = {
          fileUrl:this.upDataForm.fileUrl,
          orgId:this.upDataForm.orgId,
          stationId:this.upDataForm.stationId,
          title:this.upDataForm.title,
          userId:this.upDataForm.userId,
        }
        console.log('编辑和添加的代码还未完善,')
        jobDescDoSave(obj).then(res=>{
          if(res.code == 0){
            this.requestParams.reload = Math.random();
            this.dialogFormVisible = false;
            this.$notify({
            title: '提示',
            message: '添加成功',
            duration: 3000,
            type: 'success'
            });
          }else{
            this.$notify({
            title: '提示',
            message: res.msg,
            duration: 3000,
            type: 'warning'
            });
          }
        })
      },
      //上传成功
      successRes(res){
        this.upDataForm.fileUrl = res.response.fileRdfUrl + res.response.fileUrl;
        this.dataUp.close();
      },
      //上传失败
      errorRes(res){
        this.dataUp.close();
        this.$notify({
          title: '提示',
          message: '请检查文件类型或大小后再上传',
          duration: 3000,
          type: 'warning'
          });
      },
      //上传加载loading
      isUpdata(event,file){
        this.dataUp = Loading.service({fullscreen:true})
      },
      //返回可选列表
      searchOrg(string,cb){
        cb(this.orgNameString);
      },
      //弹框选择组织
      handleSelectOrg(item){
        this.upDataForm.orgId = item.id;
      },
      // 人员选择
      personSelect(userId){
        let obj = {};
        obj = this.options.find((item)=>{
            return item.userId === userId;//筛选出匹配数据
        });
        this.upDataForm.stationId = obj.stationId;
        this.upDataForm.userId = obj.userId;
      },
      deleteAll(){
        if(this.multipleSelection.length == 0){
          this.$notify({
          title: '提示',
          message: '请至少选择一条数据',
          duration: 3000,
          type: 'warning'
          });
          return
        }else{
          this.$confirm('确认删除已选中的履职说明书吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let str = "";
          for (var val of this.multipleSelection) {
            str += val.id;
            str += ',';
          }
          desDoDelete({ids:str}).then(res=>{
            if(res.code == 0){
              this.requestParams.reload = Math.random();//刷新数据
              this.$message({
              type: 'success',
              message: '操作成功!'
              });
            }else{
              this.$notify({
                title: '提示',
                message: res.msg,
                duration: 3000,
                type: 'warning'
              });
            }
          })
          
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
        }
      },
      //获取岗位列表
      getStationList(name){
        findStationList({name:name}).then(res=>{
          if(res.code == 0){
            if(res.response){
            this.propertyList = res.response;
            }else{
              this.propertyList = [];
            }
          }
        })
      },
      findOrg(name,callback){//搜索组织
        findOrgList({name:name}).then((res)=>{
          callback(res)
        })
      },
      //岗位输入框
      propertyMethod(string,cb){
          cb(this.propertyList);
      },
      propertyChange(data){
        this.requestParams.stationId = data.id;
      },
      // 上级组织输入框选择
      querySearchAsync(queryString, cb) {
          cb(this.restaurants);
      },
      selectOrg(item) {
        // 获取父id
        this.requestParams.orgId = item.id + '';
      },
  },
  mounted:function(){
    this.uploadUrl = uploadFile();
    this.headerToken = {
      token:localStorage['token']
    }
  },
  watch:{
    'upDataForm.pName':function(val,oldVal){
          val = val || '';
          findOrgList({name:val}).then((res)=>{
          if(res.code == 0){
            this.orgNameString = res.response; 
          }else{
            this.orgNameString = [];
          }
        })
      },
      'upDataForm.orgId':function(val,oldVal){
        if(val == ''){
          this.options = [];
        }else{
            if(val != oldVal && val){
            findPageList({orgId:val}).then(res=>{
              if(res.response.searchData){
                this.options = res.response.searchData;
              }else{
                
              }
            })
          }
        }
      },
       //岗位属性输入监听
      property(newVal,oldVal){
      if(newVal != oldVal){
        this.getStationList(newVal);
        if(newVal == ''){
          this.requestParams.stationId = ''
        }
      }
    },
      //上级输入
      pName(newValue, oldValue) {
            if(newValue != oldValue){
              this.findOrg(newValue,(res)=>{
                if(res.response){
                this.restaurants = res.response;
                }else{
                  this.restaurants = []
                }
              })
            }
    　},
      keywords(val,oldVal){
        this.requestParams.keywords = val;
      }

  }
}
</script>

<style scope>
  .jopTitle{
    height: 48px;
    background: #fff;
    margin-bottom: 25px;
    line-height: 48px;
    padding: 0 10px;
  }
 
  .el-table .cell.el-tooltip{
    text-align: center
  }
  .el-table th>.cell{
    text-align: center
  }
  .el-table .cell{
    text-align: center
  }
  .el-button+.el-button{
    margin-left: 0;
  }
</style>